//单项链表

// 定义单链表的存储结构
// 一个存储数据，一个存储下一个节点的地址

const Node = function (data, next = null) {
    this.data = data;
    this.next = next;
  }
  
  const LinkList = function () {
      this.head = null; // 初始化头节点为null
  }
  
  // 创建链表
  const initList = function () {
    return new LinkList();
  };
  
  const list = initList();
  
  // 插入节点
  const addList = function (list, data, pos = 1) {
      if (pos < 1) {
          console.log("插入位置错误");
          return;
      }
      const node = new Node(data);
      if (list.head === null) {
          // 如果链表为空，则新节点为头节点
          list.head = node;
      } else if (pos === 1) {
          // 插入到链表头部
          node.next = list.head;
          list.head = node;
      } else {
          let current = list.head;
          let previous = null;
          let currentIndex = 1;
          
          while (current !== null && currentIndex < pos) {
              previous = current;
              current = current.next;
              currentIndex++;
          }
          
          if (current === null) {
              console.log("插入位置超出链表长度");
              return;
          }
          
          node.next = current;
          previous.next = node;
      }
  }
  
  // 测试代码
  addList(list, 100);  // 插入到链表尾部（因为只有一个元素，所以也是头部）
  addList(list, 101, 1);  // 插入到链表头部
  addList(list, 102, 1);  // 插入到链表头部
  console.log(JSON.stringify(list));
  
  // 打印链表
  const printList = function(list) {
      let current = list.head;
      while (current !== null) {
          console.log(current.data);
          current = current.next;
      }
  }
  
  printList(list);  // 应该输出 101, 100